
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ESUtils {

	public static Client getClient(){
		String clusterName = "elasticsearch";

		// 程序中更改集群结点名称 并且设置client.transport.sniff为true来使客户端去嗅探整个集群的状态
		Settings settings = ImmutableSettings.settingsBuilder()
				.put("client.transport.sniff", true).put("client", true)
				.put("data", false).put("cluster.name", clusterName).build();
		/*
		* 创建客户端，所有的操作都由客户端开始，这个就好像是JDBC的Connection对象
		* 用完记得要关闭
		*/
		Client client = new TransportClient(settings)
		//// 这里可以同时连接集群的服务器,可以多个,并且连接服务是可访问的
		.addTransportAddress(new InetSocketTransportAddress("localhost", 9300));
		return client;
	}

	private static ObjectMapper objectMapper = new ObjectMapper();  
    public static String toJson(Object o){  
        try {  
            return objectMapper.writeValueAsString(o);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return "";  
    }  
		 
}
